package com.tudouji.project.d3.service.impl;

import java.sql.Time;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import com.tudouji.common.utils.DateUtils;
import com.tudouji.common.utils.StringUtils;
import com.tudouji.d3.domain.ResponseBack;
import com.tudouji.project.d3.domain.*;
import com.tudouji.project.d3.mapper.*;
import com.tudouji.project.d3.service.ILogisticRuleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tudouji.project.d3.service.ID3OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * D3平台订单Service业务层处理
 *
 * @author tudouji
 * @date 2023-03-29
 */
@Slf4j
@Service
public class D3OrderServiceImpl implements ID3OrderService {
    @Autowired
    private D3OrderMapper d3OrderMapper;
    @Autowired
    private D3OrderTodoMapper d3OrderTodoMapper;
    @Autowired
    private ILogisticRuleService logisticRuleService;
    @Autowired
    private D3OrderItemMapper d3OrderItemMapper;
    @Autowired
    private D3ProductMapper d3ProductMapper;
    @Autowired
    private D3ShopMapper d3ShopMapper;

    /**
     * 查询D3平台订单
     *
     * @param id D3平台订单ID
     * @return D3平台订单
     */
    @Override
    public D3Order selectD3OrderById(Long id) {
        return d3OrderMapper.selectD3OrderById(id);
    }

    /**
     * 查询D3平台订单列表
     *
     * @param d3Order D3平台订单
     * @return D3平台订单
     */
    @Override
    public List<D3Order> selectD3OrderList(D3Order d3Order) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        try {
            if (StringUtils.isNotEmpty(d3Order.getStartdate())) {
                Date date = simpleDateFormat.parse(d3Order.getStartdate());
//                date =  DateUtils.addDay(date, 1);
                Long l = date.getTime();
                String s = String.valueOf(l);
                d3Order.setStartdate(s);
            }
            if (StringUtils.isNotEmpty(d3Order.getEnddate())) {
                Date date1 = simpleDateFormat.parse(d3Order.getEnddate());
                date1 =  DateUtils.addDay(date1, 1);
                Long l1 = date1.getTime();
                String s1 = String.valueOf(l1);
                d3Order.setEnddate(s1);
            }
            if (StringUtils.isNotEmpty(d3Order.getBeginTime())) {
                Date date = simpleDateFormat.parse(d3Order.getBeginTime());
//                date =  DateUtils.addDay(date, 1);
                Long l = date.getTime();
                String s = String.valueOf(l);
                d3Order.setBeginTime(s);
            }
            if (StringUtils.isNotEmpty(d3Order.getEndTime())) {
                Date date1 = simpleDateFormat.parse(d3Order.getEndTime());
                date1 =  DateUtils.addDay(date1, 1);
                Long l1 = date1.getTime();
                String s1 = String.valueOf(l1);
                d3Order.setEndTime(s1);
            }
            if (StringUtils.isNotEmpty(d3Order.getFinishTimeStart())){
                Date date2=simpleDateFormat.parse(d3Order.getFinishTimeStart());
//                date2 =  DateUtils.addDay(date2, 1);
                Long l2=date2.getTime();
                String s2=String.valueOf(l2);
                d3Order.setFinishTimeStart(s2);
            }
            if (StringUtils.isNotEmpty(d3Order.getFinishTimeEnd())){
                Date date3=simpleDateFormat.parse(d3Order.getFinishTimeEnd());
                date3 =  DateUtils.addDay(date3, 1);
                Long l3=date3.getTime();
                String s3=String.valueOf(l3);
                d3Order.setFinishTimeEnd(s3);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        List<D3Order> d3Orders = d3OrderMapper.selectD3OrderList(d3Order);
        for (D3Order order : d3Orders) {
            if (StringUtils.isNotNull(order.getOrderTime())) {
                String str = order.getOrderTime();
                Long data = Long.valueOf(str);
                String data1 = sdf.format(data);
                order.setOrderTime(data1);
            }
            if (StringUtils.isNotNull(order.getFinishTime())) {
                String str1 = order.getFinishTime();
                Long data2 = Long.valueOf(str1);
                String data3 = sdf.format(data2);
                order.setFinishTime(data3);
            }
        }

        return d3Orders;
    }


    /**
     * 新增D3平台订单
     *
     * @param d3Order D3平台订单
     * @return 结果
     */
    @Override
    public int insertD3Order(D3Order d3Order) {
        d3Order.setCreateTime(DateUtils.getNowDate());
        return d3OrderMapper.insertD3Order(d3Order);
    }

    /**
     * 修改D3平台订单
     *
     * @param d3Order D3平台订单
     * @return 结果
     */
    @Override
    public int updateD3Order(D3Order d3Order) {
        d3Order.setUpdateTime(DateUtils.getNowDate());
        return d3OrderMapper.updateD3Order(d3Order);
    }

    /**
     * 批量删除D3平台订单
     *
     * @param ids 需要删除的D3平台订单ID
     * @return 结果
     */
    @Override
    public int deleteD3OrderByIds(Long[] ids) {
        return d3OrderMapper.deleteD3OrderByIds(ids);
    }

    /**
     * 删除D3平台订单信息
     *
     * @param id D3平台订单ID
     * @return 结果
     */
    @Override
    public int deleteD3OrderById(Long id) {
        return d3OrderMapper.deleteD3OrderById(id);
    }

    @Override
    @Transactional
    public ResponseBack insertOrder(D3Order d3Order) {
        try {
            D3Order order = d3OrderMapper.selectD3OrderByRefOid(d3Order.getRefOid());

            String str = d3Order.getOrderTime();
            long data = Long.valueOf(str);

            D3Shop shop = new D3Shop();
            shop.setCode(d3Order.getPosCode());
            List<D3Shop> shops = d3ShopMapper.selectD3ShopList(shop);
            if (shops.size() == 0) {
                shop.setCreateTime(DateUtils.getNowDate());
                d3ShopMapper.insertD3Shop(shop);
            } else {
                shop = shops.get(0);
            }
            /*if (null == shop.getSyncDate()){
                log.info("店铺：" + shop.getName() + ", 未设置同步时间！");
                return new ResponseBack(true, "200", "店铺：" + shop.getName() + ", 未设置同步时间！");
            }*/
           /* Date minDate = shop.getSyncDate();
            long min = minDate.getTime();
            if (min>=data){
                log.info("电商订单：" + d3Order.getRefOid() + ", 在2023-04-01之前，不做处理");
                return new ResponseBack(true, "200", "电商订单：" + d3Order.getRefOid() + ", 在2023-04-01之前，不做处理");
            }*/
            if (null == order) {
                //2023-10-23插入发货地址
                /*if (StringUtils.isNotEmpty(order.getLogisticsOrderNo()) && StringUtils.isEmpty(order.getLogisticsSendFrom())){
                    String sendFrom = logisticRuleService.getSendFromByRule(d3Order.getLogisticsOrderNo());
                    if (StringUtils.isEmpty(sendFrom)){
                        D3Shop d3Shop = d3ShopMapper.selectD3ShopByCode(d3Order.getPosCode());
                        d3Shop.setLogisticRule(0);
                        d3ShopMapper.updateD3Shop(d3Shop);
                    }else{
                        d3Order.setLogisticsSendFrom(sendFrom);
                    }

                }*/

                d3Order.setCreateTime(DateUtils.getNowDate());
                d3OrderMapper.insertD3Order(d3Order);

                List<D3OrderItem> lines = d3Order.getLines();
                if (lines.size() > 0) {
                    for (D3OrderItem item : lines) {
                        item.setCreateTime(DateUtils.getNowDate());
                        item.setD3OrderId(d3Order.getId());
                        d3OrderItemMapper.insertD3OrderItem(item);
                        D3Product product = new D3Product();
                        product.setRefskuid(item.getRefSkuId());
                        product.setRefspuid(item.getRefSpuId());
                        List<D3Product> products = d3ProductMapper.selectD3ProductList(product);
                        if (products.size() == 0) {
                            product.setTitle(item.getTitle());
                            product.setStandards(item.getStandards());
                            product.setPicurl(item.getPicUrl());
                            product.setPrice(item.getPrice());
                            product.setOuterid(item.getOuterId());
                            product.setStatus(item.getStatus());
                            product.setShopId(shop.getId());
                            product.setCreateTime(DateUtils.getNowDate());
                            d3ProductMapper.insertD3Product(product);
                        }
                    }
                }
            }
            return new ResponseBack(true, "200", null);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResponseBack(false, "E10001", "推送发⽣了错误");
        }
    }

    @Override
    @Transactional
    public ResponseBack updateOrder(D3Order d3Order) {
        try {
            D3Order order = d3OrderMapper.selectD3OrderByRefOidNoUsed(d3Order.getRefOid());
            if (null != order) {

                String str = d3Order.getOrderTime();
                long data = Long.valueOf(str);

                D3Shop shop = new D3Shop();
                shop.setCode(d3Order.getPosCode());
                List<D3Shop> shops = d3ShopMapper.selectD3ShopList(shop);
                if (shops.size() == 0) {
                    shop.setCreateTime(DateUtils.getNowDate());
                    d3ShopMapper.insertD3Shop(shop);
                } else {
                    shop = shops.get(0);
                }
                /*if (null == shop.getSyncDate()){
                    log.info("店铺：" + shop.getName() + ", 未设置同步时间！");
                    return new ResponseBack(true, "200", "店铺：" + shop.getName() + ", 未设置同步时间！");
                }*/
                /*Date minDate = shop.getSyncDate();
                long min = minDate.getTime();
                if (min>=data){
                    log.info("电商订单：" + d3Order.getRefOid() + ", 在2023-04-01之前，不做处理");
                    return new ResponseBack(true, "200", "电商订单：" + d3Order.getRefOid() + ", 在2023-04-01之前，不做处理");
                }*/

                if (null != order.getSfId()) {
                    log.info("电商订单：" + d3Order.getRefOid() + "，已生成销售订单！不能更新d3_order和明细");
                    return new ResponseBack(true, "200", null);
                }
                if (1 == order.getIsToSellform()) {
                    log.info("电商订单：" + d3Order.getRefOid() + "，已生成中间表！不能更新d3_order和明细");
                    return new ResponseBack(true, "200", null);
                }
                //去掉最大ID查询条件，把已发货的D3order全部插入
                //可能需要中间表查询最大ID条件
//                Long maxId = d3ToSellformMapper.selectMaxD3OrderId();
                if (/*order.getId() <= maxId && */(!StringUtils.equalsIgnoreCase(order.getStatus(), "SHIPPED")) && StringUtils.equalsIgnoreCase(d3Order.getStatus(), "SHIPPED")/* && StringUtils.equalsIgnoreCase(d3Order.getRefundStatus(), "NO_REFUND")*/) {
                    D3OrderTodo todo = new D3OrderTodo();
                    todo.setD3OrderId(order.getId());
                    d3OrderTodoMapper.insertD3OrderTodo(todo);
                }
                d3Order.setId(order.getId());
                //2023-10-23插入发货地址
                //2023-11-06注释--发货后物流信息暂时获取不到
                /*if (StringUtils.isNotEmpty(order.getLogisticsOrderNo()) && StringUtils.isEmpty(order.getLogisticsSendFrom())){
                    String sendFrom = logisticRuleService.getSendFromByRule(d3Order.getLogisticsOrderNo());
                    if (StringUtils.isEmpty(sendFrom)){
                        D3Shop d3Shop = d3ShopMapper.selectD3ShopByCode(d3Order.getPosCode());
                        d3Shop.setLogisticRule(0);
                        d3ShopMapper.updateD3Shop(d3Shop);
                    }else{
                        d3Order.setLogisticsSendFrom(sendFrom);
                    }

                }*/
                d3OrderMapper.updateD3Order(d3Order);
                d3OrderItemMapper.deleteD3OrderItemByD3Id(order.getId());
                List<D3OrderItem> lines = d3Order.getLines();
                if (lines.size() > 0) {
                    for (D3OrderItem item : lines) {
                        item.setCreateTime(DateUtils.getNowDate());
                        item.setD3OrderId(order.getId());
                        d3OrderItemMapper.insertD3OrderItem(item);
                    }
                }
            } else {
                log.info("电商订单：" + d3Order.getRefOid() + "，未查找到此订单！不能更新d3_order和明细");
                return new ResponseBack(true, "200", null);
            }
            return new ResponseBack(true, "200", null);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResponseBack(false, "E10001", "异常");
        }
    }
}
